package cn.tworice;

import cn.tworice.source.StringJavaSource;

import javax.tools.*;
import java.lang.reflect.Method;
import java.util.Collections;

public class DynamicClassLoaderExample {
    public static void main(String[] args) throws Exception {
        String className = "MyDynamicClass";
        String sourceCode = "public class MyDynamicClass { " +
                "public void greet() { " +
                "   System.out.println(\"你好，世界!\"); " +
                "} }";

        // 获取编译器实例
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            throw new IllegalStateException("JDK compiler not available");
        }

        // 创建文件管理器（使用修正后的版本）
        try (MemoryJavaFileManager fileManager = new MemoryJavaFileManager(compiler.getStandardFileManager(null, null, null))) {
            // 准备源码对象
            JavaFileObject source = new StringJavaSource(className, sourceCode);

            // 执行编译
            JavaCompiler.CompilationTask task = compiler.getTask(
                    null,
                    fileManager,
                    null,
                    null,
                    null,
                    Collections.singletonList(source)
            );

            if (!task.call()) {
                throw new RuntimeException("Compilation failed");
            }

            // 从FileManager获取字节码并创建ClassLoader
            MemoryClassLoader classLoader = new MemoryClassLoader(fileManager.getClassBytes());

            // 加载并使用类
            Class<?> clazz = classLoader.loadClass(className);
            Object instance = clazz.getDeclaredConstructor().newInstance();
            Method method = clazz.getMethod("greet");
            method.invoke(instance);
        }
    }
}
